<?php
namespace Base\Exception;

class Abstraction extends \Exception {

    protected $type = "";

    public function __construct($message = "", $code = 0, \Exception $previous = null) {
        $user_msg = null;

        if ($info = $this->getErrorMsgInfo($message)) {
            $key = $info['key'];
            if (!\S\Config::confError($key)) {
                $msg = $key;
            } else {
                $user_msg = \S\Config::confError($key . '.user_msg');
                $msg      = \S\Config::confError($key . '.msg');
                $code     = \S\Config::confError($key . '.retcode');
            }
        } else {
            $msg = $message;
        }

        parent::__construct($user_msg ?: $msg, $code, $previous);
        $this->setLog($message);
    }

    protected function setLog($msg) {
        $message['exception'] = $this;
        if ($info = $this->getErrorMsgInfo($msg)) {
            $message['exception_self_message'] = \S\Config::confError($info['key']);
        } else {
            $message['exception_self_message'] = $msg;
        }
        if ($info['type'] == 'inform') {
            \S\Log\Logger::getInstance()->inform($message);
        } else {
            //停止记录PHP的exception错误;
            //\S\Log\Logger::getInstance()->warning($message);
        }
    }

    public function getErrorMsgInfo($msg) {
        $err_msg_type = ['error', 'inform'];
        if (in_array($type = strstr($msg, '.', true), $err_msg_type)) {
            return ['type' => $type, 'key' => substr($msg, strlen($type) + 1, strlen($msg))];
        }
        return [];
    }

}
